import sys
from typing import List, Optional

from .model import Mail, Account, NewMail

if sys.platform == "win32":
    pass
else:
    raise ImportError(f"Cannot run on non-Windows platform {sys.platform}")


import win32com.client


class OutlookApp:
    def __init__(self):
        self.outlook = win32com.client.Dispatch("Outlook.Application")
        self.accounts = win32com.client.Dispatch(
            "Outlook.Application",
        ).Session.Accounts

    def crate_mail(self) -> NewMail:
        mail = NewMail(self.outlook.CreateItem(0))
        return mail

    def get_accounts(self) -> List[Account]:
        accounts = []
        for i in self.accounts:
            accounts.append(Account(i))

        return accounts

    def get_folder_mails(self, account: Account, folder: str):
        outlook = self.outlook.GetNamespace("MAPI")

        inbox = outlook.Folders(account.display_name)
        _folders = inbox.Folders
        for _folder in _folders:
            if str(_folder) == folder:
                return _folder.Items

        return

    def iter_mail_box(
        self,
        account: Account,
        folder: str,
        restrict: Optional[str] = None,
    ):

        inbox = self.outlook.GetNamespace("MAPI").Folders[account.display_name]
        _folder = inbox

        for i in folder.split("/"):
            _folder = _folder.Folders[i]

        mails = _folder.Items

        if restrict:
            mails = mails.Restrict(restrict)

        count: int = mails.Count

        for i in range(count - 1, -1, -1):
            mail = mails[i]
            yield Mail(mail)
